
<?php
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController {

	var $uses = array('User','SocialProfile','Tutor');
	
	public $paginate = array(
        'limit' => 25,
        'conditions' => array('status' => '1'),
    	'order' => array('User.username' => 'asc' ) 
    );
	public $components = array('Hybridauth');
	
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('login','add','social_login','social_endpoint','activate');
         $this->Security->unlockedActions = array('add','edit'); 
		
    }

	public function login() {
		
		//if already logged-in, redirect
		if($this->Session->check('Auth.User')){
			$this->redirect(array('action' => 'index'));		
		}
		
		// if we get the post information, try to authenticate
		if ($this->request->is('post')) {
			if ($this->Auth->login()) {
			
				$status = $this->Auth->user('status');
				if($status != 0){
					$this->Session->setFlash(__('Welcome, '. $this->Auth->user('username')));
					$this->redirect($this->Auth->redirectUrl());
				}else{
					// this is a deleted user
					$this->Auth->logout();
					$this->Session->setFlash(__('Invalid username or password - This user appears to be deleted...'));
				}
			} else {
				$this->Session->setFlash(__('Sai tên đăng nhập hoặc mật khẩu'),'default', array('class' => 'error'));
			}
		} 
	}

	public function admin_login() {
		

		// echo AuthComponent::password('admin');
		    $this->layout ='admin_login';

           
		if ($this->request->is('post')) {
			$user_status = $this->User->find('first',array('fields'=>'status','conditions'=>array('User.username'=>$this->request->data['User']['username'])));
			$user_roleid = $this->User->find('first',array('fields'=>'role_id','conditions'=>array('User.username'=>$this->request->data['User']['username'])));
			
			if(!empty($user_status)){
				if ($user_status['User']['status'] && $user_roleid['User']['role_id']==1){
					if ($this->Auth->login()) {
						$this->redirect($this->Auth->redirectUrl());
					} else {
						$this->Session->setFlash(__('Invalid username or password, try again'),'alert',array('class'=>'alert-error'));
					}
				}
				else {
					$this->Session->setFlash(__('User not active'),'alert',array('class'=>'alert-error'));
				}
			}
			else {
				$this->Session->setFlash(__('User not found'),'alert',array('class'=>'alert-error'));
			}
		}
	    
	
	}

  public function customer_dashboard() {
	}

////////////////////////////////////////////////////////////

	public function admin_dashboard() {
	}


	public function logout() {
		$this->Hybridauth->logout();
		$this->redirect($this->Auth->logout());
	}
	
	/* social login functionality */
	public function social_login($provider) {
		if( $this->Hybridauth->connect($provider) ){
			$this->_successfulHybridauth($provider,$this->Hybridauth->user_profile);
        }else{
            // error
			$this->Session->setFlash($this->Hybridauth->error);
			$this->redirect($this->Auth->loginAction);
        }
	}

	public function social_endpoint($provider) {
		$this->Hybridauth->processEndpoint();
	}
	
	private function _successfulHybridauth($provider, $incomingProfile){

		// #1 - check if user already authenticated using this provider before
		$this->SocialProfile->recursive = -1;
		$existingProfile = $this->SocialProfile->find('first', array(
			'conditions' => array('social_network_id' => $incomingProfile['SocialProfile']['social_network_id'], 'social_network_name' => $provider)
		));
		
		if ($existingProfile) {
			$this->User->recursive = -1;
			// #2 - if an existing profile is available, then we set the user as connected and log them in
			$user = $this->User->find('first', array(
				'conditions' => array('id' => $existingProfile['SocialProfile']['user_id'])
			));
			
			
			$this->_doSocialLogin($user,true);
		} else {
			
			// New profile.
			if ($this->Auth->loggedIn()) {
				// user is already logged-in , attach profile to logged in user.
				// create social profile linked to current user
				$incomingProfile['SocialProfile']['user_id'] = $this->Auth->user('id');
				$this->SocialProfile->save($incomingProfile);
				
				$this->Session->setFlash('Your ' . $incomingProfile['SocialProfile']['social_network_name'] . ' account is now linked to your account.');
				$this->redirect($this->Auth->redirectUrl());

			} else {
				// no-one logged and no profile, must be a registration.
				$user = $this->User->createFromSocialProfile($incomingProfile);

				$existingUser = $this->User->find('first', array(
			     'conditions' => array('email' => $incomingProfile['SocialProfile']['email'])));
				if(!$existingUser) {
				$tutor = $this->Tutor->create();
				$tutor['Tutor']['user_id'] = $user['User']['id'];
				$this->Tutor->save();

				}
				$incomingProfile['SocialProfile']['user_id'] = $user['User']['id'];
				
				$this->SocialProfile->save($incomingProfile);
				


				// log in with the newly created user
				$this->_doSocialLogin($user);
               
			}
		}	
	}
	
	private function _doSocialLogin($user, $returning = false) {
	

		if ($this->Auth->login($user['User'])) {
			if($returning){
				$this->Session->setFlash(__('Chào mừng đã quay lại, '. $this->Auth->user('username')));
			} else {
				$this->Session->setFlash(__('Cập nhật đầy đủ hò sơ gia sư, '. $this->Auth->user('username')));
			}
        
       

           if ($this->Auth->user('phone')==null) {
			$this->redirect(array('plugin'=>'','controller'=>'tutors','action'=>'edit')) ; }

			else $this->redirect(array('plugin'=>'','controller'=>'tutors','action'=>'profile'));

		
			
		} else {
			$this->Session->setFlash(__('Unknown Error could not verify the user: '. $this->Auth->user('username')));
		}
	}

    public function index() {
		$this->paginate = array(
			'limit' => 10,
			'order' => array('User.username' => 'asc' ),
			'conditions' => array('User.status' => 1),
		);
		$users = $this->paginate('User');
		$this->set(compact('users'));
    }

    public function admin_index() {

		$this->Paginator = $this->Components->load('Paginator');

		$this->Paginator->settings = array(
			'User' => array(
				'recursive' => -1,
				'contain' => array(
				),
				'conditions' => array(
				),
				'order' => array(
					'Users.name' => 'ASC'
				),
				'limit' => 20,
				'paramType' => 'querystring',
			)
		);
		$users = $this->Paginator->paginate();
		$this->set(compact('users'));
	}

	public function admin_view($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException('Invalid user');
		}
		$this->set('user', $this->User->read(null, $id));
	}
		public function admin_add() {
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash('The user has been saved');
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('The user could not be saved. Please, try again.');
			}
		}
	}
	public function admin_edit($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException('Invalid user');
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash('The user has been saved');
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('The user could not be saved. Please, try again.');
			}
		} else {
			$this->request->data = $this->User->read(null, $id);
		}
	}

////////////////////////////////////////////////////////////

	public function admin_password($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException('Invalid user');
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash('The user has been saved');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('The user could not be saved. Please, try again.');
			}
		} else {
			$this->request->data = $this->User->read(null, $id);
		}
	}

////////////////////////////////////////////////////////////

	public function admin_delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException('Invalid user');
		}
		if ($this->User->delete()) {
			$this->Session->setFlash('User deleted');
			return $this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash('User was not deleted');
		return $this->redirect(array('action' => 'index'));
	}

   	public function add() {
                $this->set('title_for_layout', __d('croogo', 'Đăng ký làm gia sư'));
                if ($this->Auth->user('username')) {
                        $this->redirect(array('controller'=>'jobs','action' => 'promoted'));
                }
                if (!empty($this->request->data)) {
                	  
                        $this->User->create();
                        $this->request->data['User']['role_id'] = 2; // Registered
                        $this->request->data['User']['activation_key'] = md5(uniqid());
                        $this->request->data['User']['status'] = 1;
                       // $this->request->data['User']['username'] = htmlspecialchars($this->request->data['User']['username']);
                        //$this->request->data['User']['facebook'] = htmlspecialchars($this->request->data['User']['facebook']);
                        //$this->request->data['User']['name'] = htmlspecialchars($this->request->data['User']['name']);
                        if ($this->User->save($this->request->data)) {
                                
                                        $this->Session->setFlash(__d('Cake', 'Bạn đã đăng ký thành công'), 'default', array('class' => 'success'));
                                        $this->redirect(array('action' => 'login'));
                                } else {
                                        $this->Session->setFlash(__d('Cake', 'Hệ thống xảy ra lỗi khi đang gởi mail.'), 'default', array('class' => 'error'));
                                }                                
                        } 
                }

    public function edit($id = null) {

		    if (!$id) {
				$this->Session->setFlash('Please provide a user id');
				$this->redirect(array('action'=>'index'));
			}

			$user = $this->User->findById($id);
			if (!$user) {
				$this->Session->setFlash('Invalid User ID Provided');
				$this->redirect(array('action'=>'index'));
			}

			if ($this->request->is('post') || $this->request->is('put')) {
				$this->User->id = $id;
				if ($this->User->save($this->request->data)) {
					$this->Session->setFlash(__('The user has been updated'));
					$this->redirect(array('action' => 'edit', $id));
				}else{
					$this->Session->setFlash(__('Unable to update your user.'));
				}
			}

			if (!$this->request->data) {
				$this->request->data = $user;
			}
    }

    public function delete($id = null) {
		
		if (!$id) {
			$this->Session->setFlash('Please provide a user id');
			$this->redirect(array('action'=>'index'));
		}
		
        $this->User->id = $id;
        if (!$this->User->exists()) {
            $this->Session->setFlash('Invalid user id provided');
			$this->redirect(array('action'=>'index'));
        }
        if ($this->User->saveField('status', 0)) {
            $this->Session->setFlash(__('User deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'));
        $this->redirect(array('action' => 'index'));
    }
	
	 /**
         * Activate
         *
         * @param string $username
         * @param string $key
         * @return void
         * @access public
         */
        public function activate($username = null, $key = null) {
        	$this->autoRender= false;
                if ($username == null || $key == null) {
                        $this->redirect(array('action' => 'login'));
                }

                $this->Session->write('user_login', 'user_login');

              
                        $user = $this->User->find('first', array('conditions' => array('User.username' => $username, 'User.role_id' => 2)));
                        //Croogo::dispatchEvent('Controller.Users.beforeActivation', $this);
                        $this->User->id = $user['User']['id'];
                        $this->User->saveField('activation_key', md5(uniqid()));
                        App::uses('CakeTime', 'Utility');
                        if (CakeTime::fromString('-2 days') <= CakeTime::fromString($user['User']['created'])) {
                                $this->User->saveField('status', 1);
                                //Croogo::dispatchEvent('Controller.Users.activationSuccessful', $this);
                                $this->Session->setFlash(__d('Cake', 'Tài khoản đã kích hoạt thành công.'), 'default', array('class' => 'success'));
                        } else {
                                //Croogo::dispatchEvent('Controller.Users.activationExpired', $this);
                                $this->Session->setFlash(__d('Cake', 'Link này đã hết hạn đăng ký.'), 'default', array('class' => 'error'));
                        }
               
                $this->redirect(array('action' => 'login'));
        }
         public function changepass($username = null, $key = null) {
                $this->set('title_for_layout', __d('Cake', 'Đổi password'));

                if ($username != null && $key != null) {
                        $user = $this->User->find('first', array(
                            'conditions' => array(
                                'User.username' => $username,
                                'User.activation_key' => $key,
                                'User.role_id' => 2
                            ),
                                ));

                        if (isset($user['User']['id'])) {
                                $this->Session->write('user_add', 'user_add');
                                App::uses('CakeTime', 'Utility');
                                if (CakeTime::fromString('-2 days') <= CakeTime::fromString($user['User']['updated'])) {
                                        $this->User->id = $user['User']['id'];
                                        $this->User->saveField('password', $user['User']['tmp_pass']);
                                        $this->User->saveField('tmp_pass', null);
                                        $this->User->saveField('activation_key', md5(uniqid()));
                                        $this->Session->setFlash(__d('croogo', 'Your password has been change successfully. Please activate link and login.'), 'default', array('class' => 'success'));
                                } else {
                                        $this->Session->setFlash(__d('croogo', 'Link is expired activation.'), 'default', array('class' => 'error'));
                                }
                        }
                        if(!$this->Auth->user('email')){
                                //Croogo::dispatchEvent('Controller.Users.beforeLogout', $this);
                                $this->redirect($this->Auth->logout());
                                //Croogo::dispatchEvent('Controller.Users.afterLogout', $this);
                        }                        
                }

                if (!empty($this->request->data)) {
                        $this->Session->write('user_add', 'user_add');
                        if (!empty($this->request->data['User']['password']) && $this->request->data['User']['password'] == $this->request->data['User']['verify_password']) {
                                $user['User'] = $this->Auth->user();
                                $this->User->id = $user['User']['id'];
                                $this->User->saveField('tmp_pass', $this->request->data['User']['password']);
                                $this->set(compact('user'));

                                //send mail
                                $email = new CakeEmail('default');
                                $email->to($user['User']['email'])
                                        ->subject(__d('cake', '[%s] Change Password'))
                                        ->template('change_password')
                                        ->viewVars(array('user' => $user));
                                if ($this->theme) {
                                        $email->theme($this->theme);
                                }
                                if ($email->send()) {
                                        $this->Session->setFlash(__d('croogo', 'Yêu cầu của bạn đã được thực hiện. Bạn hãy kiểm tra email để thay đổi mật khâu.'), 'default', array('class' => 'success'));
                                        //$this->redirect(array('action' => 'login'));
                                } else {
                                        $this->Session->setFlash(__d('croogo', 'Hệ thống xãy ra lỗi khi đang gởi mail.'), 'default', array('class' => 'error'));
                                }              
                        } else {
                                $this->Session->setFlash(__d('croogo', 'Lỗi hệ thống. Xin vui lòng thử lại.'), 'default', array('class' => 'error'));
                        }
                }
        }


}

?>